package cn.jekun.web.agent.action;

import java.sql.Types;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import cn.jekun.component.base.bean.ErrorMsg;
import cn.jekun.component.base.exceptions.BusinessException;
import cn.jekun.component.base.utils.SqlUtis;
import cn.jekun.component.core.Constants;
import cn.jekun.component.core.bean.gen.SgAccount;
import cn.jekun.component.core.bean.gen.SgSettleApply;
import cn.jekun.component.core.service.gen.SgAccountService;
import cn.jekun.component.core.service.gen.SgSettleApplyService;
import cn.jekun.web.agent.bean.Agent;
import cn.jekun.web.agent.bean.BanksAccount;
import cn.jekun.web.agent.service.BanksService;


/**
 * 银行账户管理
 * 
 * @author Mr.Dong
 *
 */
@SuppressWarnings("serial")
public class BanksAction extends AgentBaseAction {
	//private static final String AUTH_SHOP_MY_SECURITY="SHOP_MY_SECURITY";//安全设置
	private SgAccount sgAccount;

	public SgAccount getSgAccount() {
		return sgAccount;
	}

	public void setSgAccount(SgAccount sgAccount) {
		this.sgAccount = sgAccount;
	}

	public SgAccountService getSgAccountService() {
		return sgAccountService;
	}

	public void setSgAccountService(SgAccountService sgAccountService) {
		this.sgAccountService = sgAccountService;
	}

	private List<BanksAccount> resultBanksList = new ArrayList<BanksAccount>();
	private List<BanksAccount> resultIdCardsList = new ArrayList<BanksAccount>(); 
	public List<BanksAccount> getResultIdCardsList() {
		return resultIdCardsList;
	}

	public void setResultIdCardsList(List<BanksAccount> resultIdCardsList) {
		this.resultIdCardsList = resultIdCardsList;
	}

	public List<BanksAccount> getResultBanksList() {
		return resultBanksList;
	}

	public void setResultBanksList(List<BanksAccount> resultBanksList) {
		this.resultBanksList = resultBanksList;
	}
	private List<Agent> sgAccountList = new ArrayList<Agent>();
	public List<Agent> getSgAccountList() {
		return sgAccountList;
	}
	public void setSgAccountList(List<Agent> sgAccountList) {
		this.sgAccountList = sgAccountList;
	}
	@Resource(name=BanksService.BEAN_NAME)
	BanksService bankService;
	@Resource(name=SgAccountService.BEAN_NAME)
	protected SgAccountService sgAccountService;

	@Resource(name=SgSettleApplyService.BEAN_NAME)
	SgSettleApplyService sgSettleApplyService;

	@SuppressWarnings("unchecked")
	public String getBankAccountsDetails(){
		//判断是否有操作权限
		//this.checkRight(AUTH_SHOP_MY_SECURITY);
		
		JSONObject jsonObject = new JSONObject();
		
		//检测是否拥有 权限
		boolean BINDBANKCARD = this.coreAuthService.checkRigth(this.getSessionUser().getUserId(), "AGENT_MY_BANK_MANAGER_BINDBANKCARD");
		boolean REBANDINGBANKCARD = this.coreAuthService.checkRigth(this.getSessionUser().getUserId(), "AGENT_MY_BANK_MANAGER_REBANDINGBANKCARD");
		boolean SETDEFAULT = this.coreAuthService.checkRigth(this.getSessionUser().getUserId(), "AGENT_MY_BANK_MANAGER_SETDEFAULT");
		boolean UNBANDINGBANKCARD = this.coreAuthService.checkRigth(this.getSessionUser().getUserId(), "AGENT_MY_BANK_MANAGER_UNBANDINGBANKCARD");
		
		//是否出现按钮
		jsonObject.put("BINDBANKCARD",BINDBANKCARD) ;
		jsonObject.put("REBANDINGBANKCARD",REBANDINGBANKCARD) ;
		jsonObject.put("SETDEFAULT",SETDEFAULT) ;
		jsonObject.put("UNBANDINGBANKCARD",UNBANDINGBANKCARD) ;
		
		
		JSONArray jsonArray = new JSONArray();
		formMap.put("ownerId",this.getSessionUser().getAgentId()); //当前代理商ID
		String ownerId = this.getSessionUser().getAgentId();
//		this.sgAccountList = this.bankService.list("ACTION_AGENT_TS_BANKS.agentAccountList",formMap, page);
		try{
		this.sgAccountList = this.bankService.getAgentListByOwerId("ACTION_AGENT_TS_BANKS.agentAccountList", ownerId,page);
		jsonObject.element("sgAccountList", sgAccountList);
		request.setAttribute("ownerId",request.getParameter("ownerId"));
		jsonObject.element(ErrorMsg.KEY_CODE, ErrorMsg.CALL_OK);
		jsonObject.element(ErrorMsg.KEY_MESSAGE, "成功调用");
		jsonObject.put(Constants.Page.PAGE_NUMBER,page.getPageNumber());
		jsonObject.put(Constants.Page.PAGE_SIZE,page.getPageSize());
		jsonObject.put(Constants.Page.TOTAL_COUNT,page.getTotalCount());
		jsonObject.put(Constants.Page.TOTAL_PAGE,page.getPages());
		}catch (BusinessException e) {
			jsonObject = JSONObject.fromObject(e.getErrorMsg());
		} catch (Exception e) {
		    jsonObject = JSONObject.fromObject(new ErrorMsg(e.getMessage()));
		}
	    return this.writeJson(jsonObject); 
//		return "/agent/bankmanage.jsp";
	}

	/*public String getBanksParams(){
		try {
			this.resultBanksList = this.bankService.getBanks(); //获取银行列表
			this.resultIdCardsList = this.bankService.getIdCards(); //获取证件类型列表
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "/agent/bindingbankcard.jsp";
	}*/
	
	/**
	 * 身份类型
	 * @return
	 */
	public String getCardType(){
		JSONObject jsonObject = null;
		try{
		   jsonObject = new JSONObject();
		   this.resultIdCardsList = this.bankService.getIdCards(); //获取证件类型列表
           jsonObject.element("resultIdCardsList",resultIdCardsList);		   
		   jsonObject.element(ErrorMsg.KEY_CODE,ErrorMsg.CALL_OK);
           jsonObject.element(ErrorMsg.KEY_MESSAGE, "调用成功");   
           System.out.println(jsonObject);
		}catch (BusinessException e) {
			jsonObject = JSONObject.fromObject(e.getErrorMsg());
		} catch (Exception e) {
			jsonObject = JSONObject.fromObject(new ErrorMsg(e.getMessage()));
		}
		return this.writeJson(jsonObject);
	}	
	
	/**
	 * 获取银行的名字
	 * @return
	 */
	public String getBanksName(){
		JSONObject jsonObject = null;
		
		String bankId=request.getParameter("bankId");
		String bankName=request.getParameter("bankName");
		
		try{
		   jsonObject = new JSONObject();
		   this.resultBanksList = this.bankService.getBanksAgent(bankId,bankName,page);
		   JSONArray jsonArray=new JSONArray();

			HashMap<String, Object> hashMap;
			
			for(int i=0;i<this.resultBanksList.size();i++){

				
				BanksAccount tempBanksAccount=resultBanksList.get(i);
				
				hashMap=new HashMap<String, Object>();
				
				hashMap.put("bankId",tempBanksAccount.getBankNumber()==null?"":tempBanksAccount.getBankNumber());
				
				hashMap.put("bankName",tempBanksAccount.getBankName()==null?"":tempBanksAccount.getBankName());
				
				
				jsonArray.add(hashMap);


			}
			jsonObject.put("banksListData", jsonArray);
			
			jsonObject.put(Constants.Page.PAGE_NUMBER,page.getPageNumber());
			
			jsonObject.put(Constants.Page.PAGE_SIZE,page.getPageSize());
			
			jsonObject.put(Constants.Page.TOTAL_COUNT,page.getTotalCount());
			
			jsonObject.put(Constants.Page.TOTAL_PAGE,page.getPages());

			jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_OK);

			jsonObject.put(ErrorMsg.KEY_MESSAGE,"调用成功");
		}catch (BusinessException e) {
			jsonObject = JSONObject.fromObject(e.getErrorMsg());
		} catch (Exception e) {
			jsonObject = JSONObject.fromObject(new ErrorMsg(e.getMessage()));
		}
		return this.writeJson(jsonObject);
	}	
	
	
	
	/**
	 * 绑定银行卡
	 * @return
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public String getBindBankCard(){
        JSONObject jsonObject = new JSONObject();
		try {
			Map map = new HashMap();
			map.put("sgAccount", sgAccount);
			map.put(SgAccount.COL_BANK_NUMBER, sgAccount.getBankNumber());
			SqlUtis.prepareSql(map, "",
					SqlUtis.getSQLRequired(map, "a."+SgAccount.COL_BANK_NUMBER, Types.VARCHAR));
			if(!this.bankService.exists(sgAccount.getBankNumber(),this.getSessionUser().getAgentId())){
				this.bankService.getBindBankCard(sgAccount.getAccountName(), 
						sgAccount.getBankId(), sgAccount.getBankNumber(), sgAccount.getMobile(), 
						request.getParameter("defaultaccount"), 
						this.getSessionUser().getAgentId(), sgAccount.getIdentifyTypeId(), sgAccount.getIdentity(),sgAccount.getAccountType());
				this.saveActionMessage("绑定银行卡成功，银行卡号:"+sgAccount.getBankNumber());
				this.logService.addAdminAuditLog("", "绑定银行卡成功，银行卡号:"+sgAccount.getBankNumber());//记录操作日志
				jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_OK);
				jsonObject.put(ErrorMsg.KEY_MESSAGE,"绑定银行卡成功，银行卡号:"+sgAccount.getBankNumber());
	
			}else{
				jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_FAIL);
				jsonObject.put(ErrorMsg.KEY_MESSAGE,"账号(卡号):"+sgAccount.getBankNumber()+"重复,已存在相同记录!");
	            return this.writeJson(jsonObject);
//				this.saveActionError("账号(卡号):"+sgAccount.getBankNumber()+"重复,已存在相同记录!");
			}
		} catch (BusinessException e) {
			jsonObject = JSONObject.fromObject(e.getErrorMsg());
		} catch (Exception e) {
			jsonObject = JSONObject.fromObject(new ErrorMsg(e.getMessage()));
		}
		return this.writeJson(jsonObject);
//		return "/agent/bindingbankcard.jsp";
	}

	/**
	 * 解除绑定
	 * @return
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public String unBindBanks(){
		JSONObject jsonObject=new JSONObject();
		try {
			boolean isdefaultAccount  = bankService.isDefaultAccount(sgAccount.getAccountId());
			if(!isdefaultAccount){ //判断当前账户是否是唯一结算账户
				Map map = new HashMap();
				sgAccount.setDefaultFlag("0"); //是否默认为结算账户(提现标志) 1-是/0-否
				sgAccount.setAvailable("0"); //有效标志  1-有效/0-无效、解绑
//				map.put("sgAccount", sgAccount);
//				map.put(SgAccount.COL_ACCOUNT_ID, sgAccount.getAccountId());
//				SqlUtis.prepareSql(map, "",
//						SqlUtis.getSQLRequired(map, "a."+SgAccount.COL_ACCOUNT_ID, Types.VARCHAR));
//				this.sgAccountService.update(map);
				this.bankService.updateSgAccount(sgAccount, sgAccount.getAccountId());
				this.saveActionMessage("解除绑定银行账户成功，账户ID:"+sgAccount.getAccountId());
				this.logService.addShopAuditLog("", "解除绑定银行账户成功，账户ID:"+sgAccount.getAccountId());//记录操作日志
				jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_OK);
				jsonObject.put(ErrorMsg.KEY_MESSAGE,"解除绑定银行账户成功，账户ID:"+sgAccount.getAccountId());
			}else{
				this.saveActionError("当前记录为唯一结算账户!");
				this.logService.addShopAuditLog("", "解除绑定银行账户失败，账户ID:"+sgAccount.getAccountId()+","
						+ "当前记录为唯一结算账户");//记录操作日志
				jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_FAIL);
				jsonObject.put(ErrorMsg.KEY_MESSAGE,"当前记录为唯一结算账户!");
				return this.writeJson(jsonObject);
			}
			formMap.put("ownerId",this.getSessionUser().getAgentId());
		} catch (BusinessException e) {
			jsonObject = JSONObject.fromObject(e.getErrorMsg());
		} catch (Exception e) {
			jsonObject = JSONObject.fromObject(new ErrorMsg(e.getMessage()));
			e.printStackTrace();
		}
		return this.writeJson(jsonObject);
//		return "!/agent/Banks/getBankAccountsDetails.do";

	}

	/**
	 * 重新绑定
	 * @return
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public String reBindBanks(){
		JSONObject jsonObject=new JSONObject();
		try {
			Map map = new HashMap();
			sgAccount.setAvailable("1"); //有效标志  1-有效/0-无效、解绑
			map.put("sgAccount", sgAccount);
			map.put(SgAccount.COL_ACCOUNT_ID, sgAccount.getAccountId());
			SqlUtis.prepareSql(map, "",
					SqlUtis.getSQLRequired(map, "a."+SgAccount.COL_ACCOUNT_ID, Types.VARCHAR));
			this.sgAccountService.update(map);
			this.saveActionMessage("重新绑定银行账户成功，账户ID:"+sgAccount.getAccountId());
			this.logService.addShopAuditLog("", "重新绑定银行账户成功，账户ID:"+sgAccount.getAccountId());//记录操作日志
			jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_OK);
			jsonObject.put(ErrorMsg.KEY_MESSAGE,"重新绑定银行账户成功，账户ID:"+sgAccount.getAccountId());
		}catch (BusinessException e) {
			jsonObject = JSONObject.fromObject(e.getErrorMsg());
		} catch (Exception e) {
			jsonObject = JSONObject.fromObject(new ErrorMsg(e.getMessage()));
		}
		return this.writeJson(jsonObject);
//		return "!/agent/Banks/getBankAccountsDetails.do";
	}

	/**
	 * 设定为默认结算账户
	 * @return
	 */
	public String setDefaultAccounts(){
		JSONObject jsonObject=new JSONObject();
		try {
			this.bankService.setDefaultAccounts(this.getSessionUser().getAgentId(),
					sgAccount.getAccountId());
			this.logService.addShopAuditLog("", "设置默认结算账户成功，账户ID:"
					+sgAccount.getAccountId());//记录操作日志
			jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_OK);
			jsonObject.put(ErrorMsg.KEY_MESSAGE,"设置默认账户成功");
			this.saveActionMessage("设置默认账户成功");
		}catch (BusinessException e) {
			jsonObject = JSONObject.fromObject(e.getErrorMsg());
		} catch (Exception e) {
			jsonObject = JSONObject.fromObject(new ErrorMsg(e.getMessage()));
		}
		return this.writeJson(jsonObject);
//		return "!/agent/Banks/getBankAccountsDetails.do";
	}
	
	/**
	 * 删除银行卡
	 *  @return
	 *
	 */
	public String deleteBank(){
		
		JSONObject jsonObject = null;
		
		try{
			String accountId = this.request.getParameter("accountId");
			
			Map map=new HashMap();
			map.put(SgAccount.COL_ACCOUNT_ID, accountId);
			SqlUtis.prepareSql(map, SqlUtis.getSQL(map, SgAccount.COL_ACCOUNT_ID,Types.VARCHAR,SqlUtis.EQ));
			
			List<SgSettleApply> settleApplys = this.sgSettleApplyService.list(map);
			if(settleApplys.size() > 0){
				jsonObject = new JSONObject();
				jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_FAIL);
					
				jsonObject.put(ErrorMsg.KEY_MESSAGE,"该银行卡有提现操作，不允许删除");
			}else{
				jsonObject = this.bankService.deleteBank(accountId);
				
				jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_OK);
					
				jsonObject.put(ErrorMsg.KEY_MESSAGE,"删除成功");
			}
			
		}catch(BusinessException e){
			jsonObject = JSONObject.fromObject(e.getErrorMsg());
		}catch (Exception e) {
			// TODO: handle exception
			jsonObject = JSONObject.fromObject(new ErrorMsg(e.getMessage()));
		}
		
		return this.writeJson(jsonObject);
	}

}
